
#include "IWindow.h"
#include "member_BProgressBar.h"
#include "member_BWidget.h"

using namespace BWE;

member_BProgressBar::member_BProgressBar(BProgressBar* progressBar)
{
	boss = progressBar;
	ia_align = Align_Center;
	orientation = Orientation_Horizontal;
	value = 0;
	step = 1;
	range.set(0, 100);
	format = "%p%";
}
member_BProgressBar::~member_BProgressBar()
{

}

void member_BProgressBar::freshRects()
{
	const BFont* font = boss->realFont();
	BRect crect = boss->centerRect();

	contentSize = chunkSize;
	if (contentSize.width() < 1)
		contentSize.width() = font->size();
	if (contentSize.height() < 1)
		contentSize.height() = font->size();

	BSize formatSize = font->textSize(format);
	if (orientation & Orientation_Vertical)
	{
		if (contentSize.width() < formatSize.width())
			contentSize.width() = formatSize.width();
	}
	if (orientation & Orientation_Horizontal)
	{
		if (contentSize.height() < formatSize.height())
			contentSize.height() = formatSize.height();
	}


	BSize realChunkSize = chunkSize;
	if (realChunkSize.width() < 1)
		realChunkSize.width() = contentSize.width();
	if (realChunkSize.height() < 1)
		realChunkSize.height() = contentSize.height();

	float length = (float)range.size();
	Align realAlign = ia_align;
	if (orientation & Orientation_Vertical)
	{
		if (realChunkSize.width() < crect.width())
			realChunkSize.width() = crect.width();
		realChunkSize.height() = length == 0 ? 0 : int((value - range.min()) / length * crect.height());
		realAlign = Align_BottomCenter;
		if (orientation & Orientation_Reverse)
			realAlign = Align_TopCenter;
	}
	if (orientation & Orientation_Horizontal)
	{
		if (realChunkSize.height() < crect.height())
			realChunkSize.height() = crect.height();
		realChunkSize.width() = length == 0 ? 0 : int((value - range.min()) / length * crect.width());
		realAlign = Align_LeftCenter;
		if (orientation & Orientation_Reverse)
			realAlign = Align_RightCenter;
	}

	chunkRect = crect.align(realAlign, realChunkSize);

	int percent = length > 0 ? int(value / length * 100.0f) : 0;
	BString percentStr = percent;
	BString valueStr = value;
	BString minStr = range.min();
	BString maxStr = range.max();

	text.reset();
	if (format.size())
	{
		text << format;
		if (0 == text.replace("%percent", percentStr))
			text.replace("%p", percentStr);
		if (0 == text.replace("%value", valueStr))
			text.replace("%v", valueStr);
		if (0 == text.replace("%minimum", minStr))
			text.replace("%min", minStr);
		if (0 == text.replace("%maximum", maxStr))
			text.replace("%max", maxStr);
	}

	ia_textSize = font->textSize(text);
	this->adjust(crect);

	if (IRound* round = widget_member(boss)->round)
	{
		chunkPoints.reset();
		round->createInnerPoints(crect, chunkRect, chunkPoints);
	}
	else
	{
		chunkPoints.clear();
	}

}
